<script lang="ts" setup>
import { ref, unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { getValidateRulesByFs } from '#/api/common/validateByFs';
import {
  SopIsvInfoApi,
  SopIsvInfoConfig,
} from '#/api/devOperation/sop/sopIsvInfo';
import { ActionEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import { downloadByData } from '#/utils/file/download';

import { createCrudOptions, downloadTemplate } from '../data/keys';

interface Emits {
  (e: 'success'): void;
}

defineOptions({
  name: '设置秘钥',
  inheritAttrs: false,
});

const emit = defineEmits<Emits>();

const { crudBinding, appendCrudOptions } = useFs({ createCrudOptions });

const type = ref<ActionEnum.ADD | ActionEnum.VIEW>(ActionEnum.VIEW);
const formRef = ref();
const { createMessage } = useMessage();

async function formSubmit() {
  await formRef.value.submit();
  createMessage.success($t(`common.tips.${type.value}Success`));
  modalApi.close();
  emit('success');
}

function handleDownloadIsvKey() {
  const form = formRef.value.getFormData();

  const text = downloadTemplate
    .replace('{appId}', form.appId)
    .replace('{privateKeyIsv}', form.privateKeyIsv)
    .replace('{publicKeyPlatform}', form.publicKeyPlatform);

  downloadByData(text, `${form.appId}_秘钥_${Date.now()}.txt`);
}

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    type.value = modalApi.getData()?.type ?? false;
    const isvId = modalApi.getData()?.isvId;

    modalApi.setState({ showConfirmButton: type.value === ActionEnum.ADD });

    const form = await SopIsvInfoApi.getKeys(isvId);

    formRef.value.setFormData(form, { mergeForm: false });

    if (unref(type) !== ActionEnum.VIEW) {
      const validateApi = SopIsvInfoConfig.UpdateKeys;
      const formOptions = await getValidateRulesByFs({
        Api: validateApi,
        mode: unref(type),
      });
      appendCrudOptions({ ...formOptions });
    }
  },
  onConfirm: formSubmit,
});
defineExpose(modalApi);
</script>

<template>
  <Modal :title="$t(`common.title.${type}`)" class="w-[60%]">
    <div class="common-form">
      <FsForm ref="formRef" v-bind="crudBinding[`${type}Form`]" :mode="type" />
    </div>
    <template #prepend-footer>
      <Button @click="handleDownloadIsvKey">下载开发者秘钥</Button>
    </template>
  </Modal>
</template>
